<template>
  <div v-if="config" class="query-link">
    <!-- <div class="table-title"> -->
    <Icon class="custom-btn-add" type="ios-add-circle" @click="addQueryLink" />
    <!-- </div> -->

    <div class="rules-cell" v-for="(item, idx) of config" :key="idx">
      <div class="rules-cell-title">
        <o-i18n-selector
          v-model="item.groupTitle"
          @on-dochange="handleConfigChange"
          :placeholder="$srv.getI18nByValue('请输入分组名称')"
        ></o-i18n-selector>
        <Input
          type="text"
          @click.native="fieldTrans(item.groupID, item.fieldID, item)"
          :placeholder="$srv.getI18nByValue('请选择该分组字段')"
          v-model="item.fieldTitle"
          readonly
        />
        <div class="rules-cell-btns">
          <Icon type="md-close" @click="removeGroup(idx)" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Watch, Model, Vue } from 'vue-property-decorator';
import { Tsrv } from '@/services';

@Component
export default class oFieldGroupbySetting extends Vue {
  @Model('modelchange') config: any;

  @Prop() sourceFields: any;

  private groupedFields = new Map<string, any[]>();

  created() {}

  mounted() {}

  private handleConfigChange(e) {
    this.$emit('modelchange', this.config);
    // this.$emit('change');
  }

  private addQueryLink() {
    this.config.push({
      groupID: Tsrv.getSnowIDFmtStr(),
      groupTitle: '',
      fieldID: [],
      fields: [],
      fieldTitle: ''
    });
    this.$emit('modelchange', this.config);
    this.$emit('change');
  }

  /**
   * 移除联查
   */
  private removeGroup(index: number) {
    this.config.splice(index, 1);
    this.$emit('modelchange', this.config);
    this.$emit('change');
  }

  /**
   * @description:穿梭框选择字段回调函数
   * @param  id // 分组id
   * @param  fieldArr // 分组字段id数组
   * @param  item // 当前分组对象
   * @return void
   * @author: swc
   * @Date: 2023-011-20 20:46:45
   * @LastEditors: swc
   * @LastEditTime: Do not edit
   */
  public fieldTrans(id: number, fieldArr: number[], item) {
    this.$emit('on-open-change');
    this.setGroupedFields();
    this.$nextTick(() => {
      if (!Tsrv.utils.noValue(item.groupTitle)) {
        // 穿梭框 源数据
        const sourceFields = [];
        const unselectFields = [];
        this.groupedFields.forEach((val, idx) => {
          if (idx !== item.groupTitle) {
            unselectFields.push(...val);
          }
        });
        this.sourceFields.forEach(el => {
          if (!unselectFields.includes(el.key)) {
            sourceFields.push(el);
          }
        });

        Tsrv.utils
          .createModal('o-transfer', {
            modalTitle: '选择字段',
            transferTitle: ['未选字段', '已选字段'],
            filterable: true,
            data: sourceFields,
            targetKeys: fieldArr
          })
          .then(data => {
            data && this.fieldChange(id, data, fieldArr, item);
            this.$emit('change');
            this.$emit('modelchange', this.config);
          });
      } else {
        // 先输入分组名
        this.$Message.info('先输入分组名');
      }
    });
  }

  /**
   * @description:分组字段改变，整理当前分组对象
   * @param  id // 分组id
   * @param  newArr // 新的分组字段id组
   * @param  oldArr // 旧的分组字段id组
   * @param  group // 当前分组对象
   * @return void
   * @author: swc
   * @Date: 2023-011-20 20:46:45
   * @LastEditors: swc
   * @LastEditTime: Do not edit
   */
  public fieldChange(
    id: number,
    newArr: number[],
    oldArr: number[],
    group: any
  ) {
    const title: string[] = [];
    const fields: string[] = [];
    const add: number[] = [];
    const del: number[] = [];
    const find: any = Tsrv.utils.find(this.config, el => el.groupID === id);
    newArr.forEach(el => {
      const tit: any = Tsrv.utils.find(
        this.sourceFields,
        item => item.key === el
      );
      tit && title.push(Tsrv.getI18nBySrv(tit.label));
      tit && fields.push(tit.label);
    });
    if (find) {
      // find.fieldID = newArr;
      find.fieldTitle = title.join(',');
      find.fields = fields;
    }
    newArr
      .filter(value => oldArr.indexOf(value) === -1)
      .forEach(el => {
        add.push(el);
      });
    add.length && this.fieldAdd(id, add, find);
    oldArr
      .filter(value => newArr.indexOf(value) === -1)
      .forEach(el => {
        del.push(el);
      });
    del.length && this.fieldDel(id, del, find);
    // 整理字段
  }

  public fieldAdd(id: number, arr: number[], group: any) {
    arr.forEach(el => {
      group.fieldID.push(el);
    });
  }

  public fieldDel(id: number, arr: number[], group: any) {
    arr.forEach(el => {
      Tsrv.utils.remove(group.fieldID, item => item === el);
    });
  }

  public setGroupedFields() {
    const config: any = Tsrv.utils.clone(this.config, true);
    this.groupedFields.clear();
    const groupedFields = this.groupedFields;
    config.forEach(item => {
      groupedFields.set(item.groupTitle, [...item.fieldID]);
    });
  }
}
</script>

<style scoped lang="scss">
.query-link {
  .table-title {
    // margin-top: 10px;
    height: 30px;
    line-height: 30px;
    .ivu-icon {
      float: left;
      margin-top: 5px;
      font-size: 18px;
    }
  }
  .custom-btn-add {
    cursor: pointer;
  }
  .rules-cell {
    padding-top: 5px;
    .ivu-icon {
      cursor: pointer;
      font-size: 18px;
    }
    .rules-cell-title {
      width: 100%;
      height: 30px;
      line-height: 30px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      :not(:last-child) {
        margin-right: 3px;
      }
      span {
        float: left;
      }
      ::v-deep .ivu-input-wrapper {
        border: 1px solid #d7dde4;
        border-radius: 5px;
        .ivu-input {
          background-color: transparent;
          border-top: 0;
          border-left: 0;
          border-right: 0;
          cursor: pointer;
        }
      }
      .rules-cell-btns {
        float: right;
        display: flex;
        align-items: center;
        button {
          margin-right: 10px;
        }
      }
    }
  }
}
</style>
